package com.xt.purchasingsystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xt.purchasingsystem.dto.SysUsersDto;
import com.xt.purchasingsystem.mapper.SysMenusMapper;
import com.xt.purchasingsystem.mapper.SysUserRoleMapper;
import com.xt.purchasingsystem.mapper.SysUsersMapper;
import com.xt.purchasingsystem.model.SysMenus;
import com.xt.purchasingsystem.model.SysUserRole;
import com.xt.purchasingsystem.model.SysUsers;
import com.xt.purchasingsystem.service.SysUsersService;
import com.xt.purchasingsystem.utils.Result;
import com.xt.purchasingsystem.utils.ResultFactory;
import com.xt.purchasingsystem.utils.SysMenuUtil;
import com.xt.purchasingsystem.utils.UserUtil;
import com.xt.purchasingsystem.vo.Menu;
import com.xt.purchasingsystem.vo.SysUsersVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author yhp
 * @since 2020-05-18
 */
@Service
public class SysUsersServiceImpl extends ServiceImpl<SysUsersMapper, SysUsers> implements SysUsersService {
    @Autowired
    private SysUsersMapper sysUsersMapper;

    @Autowired
    private SysMenusMapper sysMenusMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    public Result updateUserStatusByIdFallback(String id, Integer status) {
        return ResultFactory.buildErrorResult("用户服务繁忙,请稍后再试");
    }

    @Transactional
//    @HystrixCommand(fallbackMethod = "updateUserStatusByIdFallback", commandProperties = {
//            @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),// 是否开启断路器
//            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),// 请求次数
//            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"), // 时间窗口期
//            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60"),// 失败率达到多少后跳闸
//    })
    @Override
    public Result updateUserStatusById(String id, Integer status) {
        int i = sysUsersMapper.updateUserStatusById(id, status);
        if (i == 1) {
            return ResultFactory.buildSuccessResult("修改成功");
        } else {
            return ResultFactory.buildFailResult("修改失败");
        }
    }

    public Result authorizationRoleByUserFallback(String userId, List<String> roles) {
        return ResultFactory.buildErrorResult("用户服务繁忙,请稍后再试");
    }

    @Override
    @Transactional
//    @HystrixCommand(fallbackMethod = "authorizationRoleByUserFallback", commandProperties = {
//            @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),// 是否开启断路器
//            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),// 请求次数
//            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"), // 时间窗口期
//            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60"),// 失败率达到多少后跳闸
//    })
    public Result authorizationRoleByUser(String userId, List<String> roles) {
        int i = sysUserRoleMapper.delete(new QueryWrapper<SysUserRole>().eq("user_id", userId));

        if (roles.size() > 0) {
            for (String roleId : roles) {
                sysUserRoleMapper.insert(new SysUserRole(userId, roleId));
            }
        }
        return ResultFactory.buildSuccessResult("授权成功");
    }

    @Override
    public Result saveUser(SysUsers sysUsers) {
        HashMap<String, String> stringStringHashMap =
                UserUtil.encryptedPassword(sysUsers.getPassword());
        for (String s : stringStringHashMap.keySet()) {
            if (s.equals("salt")) {
                String salt = stringStringHashMap.get(s);
                sysUsers.setSalt(salt);
            }
            if (s.equals("password")) {
                String password = stringStringHashMap.get(s);
                sysUsers.setPassword(password);
            }
        }
        int i = sysUsersMapper.insert(sysUsers);
        if (i > 0) {
            return ResultFactory.buildSuccessResult("添加成功");
        } else {
            return ResultFactory.buildFailResult("添加失败");
        }
    }

    public Result queryMenuByUserFallback(String loginId) {
        return ResultFactory.buildErrorResult("用户服务繁忙,请稍后再试");
    }

    @Override
//    @HystrixCommand(fallbackMethod = "queryMenuByUserFallback", commandProperties = {
//            @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),// 是否开启断路器
//            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),// 请求次数
//            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"), // 时间窗口期
//            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60"),// 失败率达到多少后跳闸
//    })
    public Result queryMenuByUser(String loginId) {
        List<Menu> menusList = sysMenusMapper.queryMenusByUser(loginId);
        List<Menu> menus = new ArrayList<Menu>();
        for (Menu m : menusList) {
            if (m.getParentId() != null) {
                if (!m.getParentId().equals("4") && !m.getParentId().equals("3") && !m.getParentId().equals("2")) {
                    menus.add(m);
                }
            } else {
                menus.add(m);
            }

        }
        List<Menu> menuTree = SysMenuUtil.getMenuTree(menus);
        return ResultFactory.buildSuccessResult("查询成功", menuTree);

    }


    public Result queryMenuByUserAndParentMenuFallback(String userId, String parentId) {
        return ResultFactory.buildErrorResult("用户服务繁忙,请稍后再试");
    }

    @Override
//    @HystrixCommand(fallbackMethod = "queryMenuByUserAndParentMenuFallback", commandProperties = {
//            @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),// 是否开启断路器
//            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),// 请求次数
//            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"), // 时间窗口期
//            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60"),// 失败率达到多少后跳闸
//    })
    public Result queryMenuByUserAndParentMenu(String userId, String parentId) {
        List<SysMenus> menusList = sysMenusMapper.queryMenuByUserAndParentMenu(userId, parentId);
        System.out.println(menusList);
        return ResultFactory.buildSuccessResult("查询成功", menusList);
    }

    @Override
    public Result querySysUsersBySysUsersDto(SysUsersDto sysUsersDto) {
        List<SysUsersVo> sysUsersVos = sysUsersMapper.querySysUsersBySysUsersDto(sysUsersDto);

        PageHelper.startPage(sysUsersDto.getCurrNo(), sysUsersDto.getPageSize());
        PageInfo<SysUsersVo> pageInfo = new PageInfo<>(sysUsersVos);
        return ResultFactory.buildSuccessResult("查询成功", pageInfo);


    }
}
